<?php
namespace Unicom\Controller;
use Think\Controller;

define("API_KEY", 'J5OGQFOJ6K7EO34D');

/**
 * 联通cp
 */


class ApiController extends Controller {

	/**
	 * 上行确认接口 确认上行短信号码是否合法  弃
	 * 接口调用者 ：短信网关
	 * @param string monum  上行端口号
	 * @param string mocontent 上行内容
	 * @param string mophone  上行手机号
	 * @param string motime  上行时间  yyyyMMddhhmmss
	 * @param string linkid
	 * @param string sin 签名 sin = MD5( linkid + mophone + monum + mocontent + motime + key )
	 *
	 *
	 * @return json 格式 linkid string mtstatus string 0，允许下行；否则不下行
	 *///ARN: {"spnum":"10655572","content":"WD","mobile":"15519833791","sendtime":"20170725110115","seqid":"3937333331323535","sin":"c194007481f0133c09c7d71d4725f1a8"}
	public function verifyPhone() {

		$param = file_get_contents('php://input');
		\Think\Log::write($param, 'WARN');
		$input = json_decode($param, TRUE);

		$monum = $input['spnum'];
		$mocontent = $input['content'];
		$mophone = $input['mobile'];
		$motime = $input['sendtime'];
		$linkid = $input['seqid'];

		$sin = $input['sin'];
		$sigstr = $monum . $mocontent . $mophone . $motime . $linkid . API_KEY;
		$sig = md5($sigstr);
		\Think\Log::write($sig, 'WARN');
		\Think\Log::write('sigs=' . $sigstr, 'WARN');
		$result = array('seqid' => $linkid);

//        if (!$this->checkProvince($mophone)){
//            $result['status'] = "5";
//            $this->ajaxReturn($result);
//            return;
//        }
		if (substr($mocontent, 0, 2) != "WX") {
			if ($sin == $sig) {
				$model = M('cp.verify_phone', 'cp_');
				$data = array('linkid' => $linkid, 'mophone' => $mophone, 'mocontent' => $mocontent, 'monum' => $monum, 'motime' => $motime);
				if ($data && (!isBlackList($mophone))) {

					if ($model->add($data)) {
						$result['status'] = "0";
					} else {
						$result['status'] = "1";
					}
				} else {
					$result['status'] = "2";
				}
			} else {
				$result['status'] = "3";
			}
		} else {
			$result['status'] = "4";
		}

		$this->ajaxReturn($result);

	}

	/**
	 *状态报告同步接口
	 *接口说明
	 *下行成功之后，网关通过此接口将用户点播下行状态及包月扣费成功状态数据同步给业务系统。
	 *接口提供者：业务系统
	 *接口调用者：短信网关
	 *@param string linkid
	 *@param string phone
	 *@param string servnum
	 *@param string payfee  单位：分
	 *@param string paytime 格式：yyyyMMddhhmmss
	 *@param string msgtype  2,点播，3包月扣费
	 *@param string status  0，成功；否则失败
	 *@param string sin 签名信息 sin = MD5( linkid + phone + servnum + payfee + paytime + status + key )
	 *
	 *@return json   linkid string  status string 0：成功接收 / 1：异常
	 */
	public function syncPayment() {
		$param = file_get_contents('php://input');
		\Think\Log::write($param, 'WARN');
		$input = json_decode($param, TRUE);
		$linkid = $input['seqid'];
		$phone = $input['mobile'];
		$servnum = $input['spnum'];
		$payfee = $input['payfee'];
		$paytime = $input['paytime'];
		$msgtype = $input['msgtype'];
		$status = $input['status'];
		$seqid = $input['seqid'];
		$cmd = $input['cmd'];
		$serviceid = $input["serviceid"];
		$sin = $input['sin'];
		$sigstr = $linkid . $phone . $servnum . $cmd . $serviceid . $payfee . $paytime . $status . $msgtype . API_KEY;
		$sig = md5($sigstr);
		\Think\Log::write($sig, 'WARN');
		\Think\Log::write($sigstr, 'WARN');
		$result = array('seqid' => $linkid);
		if ($sin == $sig) {
			$model = M('cp.payment_log', 'cp_');
			$data = array('linkid' => $linkid, 'phone' => $phone,'payfee'=>$payfee, 'servnum' => $servnum, 'paytime' => $paytime, 'status' => $status, 'msgtype' => $msgtype, 'serviceid' => $serviceid);
			if ($data) {

				$id = $model->add($data);
				if ($id) {
					$result['status'] = "0";
					if ($data['msgtype'] == 2 && $data['status'] == 0) {
						$syncdata = M('cp.payment_log', 'cp_')->query("select p.phone,p.linkid,p.payfee,p.paytime,p.servnum,v.mocontent as servcode from cp.cp_payment_log as p inner join cp.cp_verify_phone as v on p.linkid=v.linkid where p.id=" . $id)[0];
						//$veryModel = M('cp.verify_phone','cp_')->where(array('linkid'=>$data['linkid']));
						if (strcasecmp($syncdata['servcode'], 'WX1234') == 0) {
							$this->syncData2("http://114.113.148.220/api/weituxinxi.jsp", $syncdata, $id); //WX1234点播推广
						} else if (strcasecmp($syncdata['servcode'], 'WX2') == 0) {
							$this->syncData2("http://114.113.148.220/api/weituxinxi.jsp", $syncdata, $id); //WX2点播推广
						} else if (strcasecmp($syncdata['servcode'], 'WX3') == 0) {
							$this->syncData2("http://114.113.148.220/api/weituxinxi.jsp", $syncdata, $id); //WX3点播推广
						} else if (strcasecmp($syncdata['servcode'], 'WX4') == 0) {
							$this->syncData2("http://114.113.148.220/api/weituxinxi.jsp", $syncdata, $id); //WX4点播推广
						} else if (strcasecmp($syncdata['servcode'], 'WX5678') == 0) {
							$this->syncData2('http://120.26.74.105/interface/weitu_momr.php', $syncdata, $id); //5678推广
						} else if (strcasecmp($syncdata['servcode'], 'WX81') == 0) {
							$this->syncData2('http://211.149.239.204:8001/GetWTData.aspx', $syncdata, $id); //wx81推广
						} else if (strcasecmp($syncdata['servcode'], 'WX82') == 0) {
							$this->syncData2('http://211.149.239.204:8001/GetWTData.aspx', $syncdata, $id); //wx82推广
						}

					}

				} else {
					$result['status'] = "1";
				}
			} else {
				$result['status'] = "2";
			}
		} else {
			$result['status'] = "3";
		}
		$this->ajaxReturn($result);
	}

	/**
	 *包月订购关系同步接口
	 *接口说明
	 *用户定制包月业务成功之后，网关通过此接口将包月订购数据同步给业务系统。（仅同步订购成功信息，话单计费成功信息由5.3接口提供）
	 *接口提供者：业务系统
	 *接口调用者：短信网关
	 *@param string phone 手机号
	 *@param string servnum 上行端口号
	 *@param string servcode 业务代码
	 *@param string payfee 计费金额 单位：分
	 *@param string paytime 时间 格式：yyyyMMddhhmmss
	 *@param string status 状态码 0，成功；否则失败 phone+servnum+servcode+payfee+paytime+status+key
	 *@param string sin 签名  sin = MD5(linked+ phone + servnum + servcode + payfee + paytime + status + key )
	 *@param  string linkid字段
	 *
	 * {"seqid":"","mobile":"15627277468","spnum":"10655572","cmd":"","serviceid":"WTD","payfee":"1000","paytime":"20170725105851","status":"0","sin":"28640fc2266051cb3c36e31ecc152119"}
	 *@return json status 0：成功接收 / 1：异常 sin = MD5(seqid+ mobile + spnum+cmd + serviceid + payfee + paytime + status + key )WARN: {"seqid":"3931373033363239","mobile":"18688102370","spnum":"10655572","cmd":"WD","serviceid":"WTD","payfee":"1000","paytime":"20170803155108","status":"0","sin":"be4bc5a4d58a593b1eea947dbbaad026"}


	 */
	public function syncOrder() {
		$param = file_get_contents('php://input');
		\Think\Log::write($param, 'WARN');
		$input = json_decode($param, TRUE);
		$phone = $input['mobile'];
		$servnum = $input['spnum'];
		$servcode = $input['serviceid'];
		$payfee = $input['payfee'];
		$paytime = $input['paytime'];
		$status = $input['status'];
		$linkid = $input['seqid'];
		$cmd = $input["cmd"];

		$sin = $input['sin'];
		$sigstr = $linkid . $phone . $servnum . $cmd . $servcode . $payfee . $paytime . $status . API_KEY;
		$sig = md5($sigstr);
		\Think\Log::write($sig, 'WARN');
		\Think\Log::write($sigstr, 'WARN');
		$result = array('seqid' => $linkid);
		if ($sin == $sig) {
			$model = M('cp.order_log', 'cp_');
			$data = array('phone' => $phone, 'servnum' => $servnum, 'servcode' => $servcode, 'payfee' => $payfee, 'paytime' => $paytime, 'status' => $status, 'linkid' => $linkid);
			if ($data) {
				$id = $model->add($data);
				if ($id) {
					$result['status'] = "0";

					if (strcasecmp($servcode, 'WTD') == 0) {
						//$this->syncData("http://114.113.148.220/api/weituxinxi_baoyue.jsp", $data, $id); // 同步给中梦
						$this->syncData($data, $id); // 同步
					} else if (strcasecmp($servcode, 'WTS') == 0) {

						$this->syncData($data, $id); // 同步给中手游ws
					} else if (strcasecmp($servcode, 'WTV') == 0) {
						$this->syncData($data, $id); // 同步给中梦
					} else {
						\Think\Log::write("没有同步..." . $servcode, 'WARN');
					}

				} else {
					$result['status'] = "1";
				}
			} else {
				$result['status'] = "2";
			}
		} else {
			$result['status'] = "3";
		}
		$this->ajaxReturn($result);

	}

	/**
	 * 同步数据到包月推广公司
	 *
	 * @return [type] [description]
	 */
	private function syncData($data, $id) {
		$syncData = M('cp.syncinterface', 'cp_')->where(array('servcode' => $data['servcode']))->find();
		$sync_url = $syncData['url'];
		if (empty($sync_url)) {
			return;
		}
		\Think\Log::write('同步url...' . $sync_url, 'WARN');

		if (is_array($data)) {
			if ($this->statCount($data['servcode'])) {
				$data['linkid'] = time() . rand(1, 1000);
				//	$data['phone']=replaceMobile($data['phone']);
				$result = send_post($sync_url, $data);
				\Think\Log::write("包月已经同步.." . $data['servcode'] . $result, 'WARN');
				\Think\Log::write($data['linkid'] . '-' . $data['phone'], 'WARN');
				//echo $result;
			} else {
				$model = M('cp.order_log', 'cp_');
				$model->where(array('id' => $id))->setField('sync', 1);
				\Think\Log::write('包月没有同步...' . $data['servcode'], 'WARN');
			}

		}

	}

	private function syncDataByGet($url, $data, $id) {

		if (is_array($data)) {
			if ($this->statCount($data['servcode'])) {
				//	$data['phone']=replaceMobile($data['phone']);
				$result = send_get($url, $data);
				\Think\Log::write("包月已经同步.." . $data['servcode'] . $result, 'WARN');
				//echo $result;
			} else {
				$model = M('cp.order_log', 'cp_');
				$model->where(array('id' => $id))->setField('sync', 1);
				\Think\Log::write('包月没有同步...' . $data['servcode'], 'WARN');
			}

		}

	}

	// /**
	//  * 同步数据到包月推广公司
	//  *
	//  * @return [type] [description]
	//  */
	// private function syncDataGet($url, $data, $id) {

	// 	if (is_array($data)) {
	// 		if ($this->statCount($data['servcode'])) {
	// 			//	$data['phone']=replaceMobile($data['phone']);
	// 			$result = send_get($url, $data);
	// 			\Think\Log::write("包月已经同步.." . $data['servcode'] . $result, 'WARN');
	// 			//echo $result;
	// 		} else {
	// 			$model = M('cp.order_log', 'cp_');
	// 			$model->where(array('id' => $id))->setField('sync', 1);
	// 			\Think\Log::write('包月没有同步...' . $data['servcode'], 'WARN');
	// 		}

	// 	}

	// }

	/**
	 * 同步数据到点播推广公司
	 *
	 * @return [type] [description]
	 */
	private function syncData2($url, $data, $id) {

		if ($this->statCount2($data['servcode'])) {

			$result = send_post($url, $data);

			\Think\Log::write($result, 'WARN');
		} else {
			$model = M('cp.payment_log', 'cp_');
			$model->where(array('id' => $id))->setField('sync', 1);
			\Think\Log::write('点播没有同步...' . $data['servcode'], 'WARN');
		}

	}

	/**
	 * 统计包月请求次数
	 * @return [type] [description]
	 */
	private function statCount($servcode) {
		$count = S($servcode);
		S($servcode, $count + 1);
		$no_sync = M('cp.config', 'cp_')->where(array('key' => $servcode))->find()['value'];
		if (empty($no_sync)) {

			return true;
		}
		$no_sync = explode(",", $no_sync);

		$index = $count % 50;
		\Think\Log::write('no_sync...' . $no_sync . '*****' . $index, 'WARN');
		if (in_array($index, $no_sync)) {
			return false;
		}

		return true;
	}

	/**
	 * 统计点播请求次数
	 * @return [type] [description]
	 */
	private function statCount2($servcode) {
		$count = S($servcode);
		S($servcode, $count + 1);
		$no_sync = M('cp.config', 'cp_')->where(array('key' => $servcode))->find()['value'];
		if (empty($no_sync)) {

			return true;
		}
		$no_sync = explode(",", $no_sync);

		$index = $count % 50;
		if (in_array($index, $no_sync)) {
			return false;
		}

		return true;

	}

	/**
	 * {"monum":"10655572","mocontent":"WY1234","mophone":"18588520588","motime":"20160506174157",
	 * "linkid":"3431383834373135","sin":"dc313f7b367b38919884ade6daeede23"}
	 * @return [type] [description]
	 * sin = MD5( linkid + mophone + monum + mocontent + motime + key )
	 * {"monum":"10655572","mocontent":"WX1234","mophone":"18588520588","motime":"20160509101159",
	 * "linkid":"3738353936383334","sin":"4eacc81b331616840bce02586a96f3d5"}
	 *
	 * [ 2016-06-03T11:34:33+08:00 ] 101.71.50.45 /cp/api/syncPayment
	WARN: {"linkid":null,"phone":"15615701728","servnum":"10655572","payfee":"1000","paytime":"20160603113329","status":"255","msgtype":"3","sin":"8d2bf4b5aeb7a2e97d4555f07fd40451"}
	[ 2016-06-03T11:34:33+08:00 ] 101.71.50.45 /cp/api/syncPayment
	WARN: a74a22e4f1322e8927d8ec157d47a3fc
	[ 2016-06-03T11:34:33+08:00 ] 101.71.50.45 /cp/api/syncPayment
	INFO: [ app_init ] --START--
	INFO: Run Behavior\BuildLiteBehavior [ RunTime:0.000016s ]
	INFO: [ app_init ] --END-- [ RunTime:0.000273s ]
	 */

	public function test() {
		// \Think\Log::write("test..", 'WARN');
		// if ($this->statCount("WTV")) {
		// 	echo "同步";
		// }
		// var_dump($d);
		$model = M('cp.order_log', 'cp_');
		$data = $model->query("select phone,servnum,servcode,payfee,paytime,linkid from cp.cp_order_log where servcode='WTS'  order by create_time desc limit 2");
		//$data[3]['sign'] = 'bjlyml';
		//$ret = $this->syncData("http://220.231.155.108:16281/data/toall277.aspx", $data[3], $id); //
		//$ret = send_post("http://218.95.37.4:10901/recv44.aspx", $data[0]);

		for ($i = 0; $i < 2; $i++) {
			// $ret = send_post("http://sync.ainipay.com/spimpl/smsdb/wt/ltdx/1259/receive", $data[$i]);
			// var_dump($ret);
		}
		var_dump($data[0]);

	}

	//模拟同步
	public function sync($servcode) {
		$syncData = M('cp.syncinterface', 'cp_')->where(array('servcode' => $servcode))->find();
		$sync_url = $syncData['url'];
		if (empty($sync_url)) {
			return;
		}
		$model = M('cp.order_log', 'cp_');
		$data = $model->query("select phone,servnum,servcode,payfee,paytime,linkid from cp.cp_order_log where servcode='$servcode'  order by create_time desc limit 1");
		//$data[3]['sign'] = 'bjlyml';
		$post_url = "";
		$param = "?";
		foreach ($data[0] as $key => $value) {
			$p = "$key=$value&";
			$param = $param . $p;

		}
		//var_dump($data[0]);
		$post_url = $sync_url . $param;

		$ret = send_post($sync_url, $data[0]);
		$result['url'] = $post_url;
		$result['code'] = $ret;
		$this->ajaxReturn($result);

	}
	public function say() {
		$kou = "";
		$no_sync = explode(",", $kou);
		if (empty($kou)) {
			var_dump("empty");
			return;
		}
		$b = in_array(1, $no_sync);
		var_dump($no_sync, $b);
	}

	  public function checkProvince($phone){
	    $model = M('cp.order_log', 'cp_');
	    $block = $model->query("select * from cp.cp_allow_provence where product_id=1")[0]['provence'];
        //$block="湖北,湖南,广东,上海,内蒙,宁夏,江苏,江西,海南,甘肃,云南,陕西,福建";

        $sql="select p.dcprivence  from (select {$phone} as cal) as a
		left join cp.cp_privence as p on left (a.cal,7)=p.dcmobile
		;";

         $model = M('cp.order_log', 'cp_');
         $data = $model->query($sql)[0]['dcprivence'];

         // var_dump(strpos($block,$data)!==false);
         return strpos($block,$data)!==false;

	}

}